package net.esj.basic.core.engine.resource;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import net.esj.basic.utils.GetClassLoader;

import org.apache.log4j.Logger;

public class ApplicationResourceBundler implements ResourceBundler {

	private static final Logger log = Logger.getLogger( ApplicationResourceBundler.class.getName() );
	
	private String bundleName;
	
	private Map<Locale,ResourceBundle> cacheBundle = new HashMap<Locale,ResourceBundle>();
	
	public ApplicationResourceBundler(String bundleName) {
		this.bundleName = bundleName;
	}
	
	@Override
	public ResourceBundle getResourceBundle(Locale locale) {
		synchronized (this.cacheBundle) {
			
			ResourceBundle rb = cacheBundle.get(locale);
			if(rb!=null){
				return rb;
			}
			ClassLoader classLoader = GetClassLoader.fromContext();
			if ( classLoader != null ) {
				rb = loadBundle(
						classLoader, locale, bundleName
						+ " not found by thread local classloader"
				);
			}
			if ( rb == null ) {
				classLoader = GetClassLoader.fromClass( ApplicationResourceBundler.class );
				rb = loadBundle(
						classLoader, locale, bundleName
						+ " not found by validator classloader"
				);
			}
			if ( rb != null ) {
				log.debug( bundleName+" found.");
			}
			else {
				log.debug( bundleName+" not found." );
			}
			cacheBundle.put(locale, rb);
			return rb;
		}
	}
	
	protected ResourceBundle loadBundle(ClassLoader classLoader, Locale locale, String message) {
		ResourceBundle rb = null;
		try {
			rb = ResourceBundle.getBundle(
					bundleName, locale,
					classLoader
			);
		}
		catch ( MissingResourceException e ) {
			log.trace( message );
		}
		return rb;
	}

}
